<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="portal" uri="/WEB-INF/portal.tld" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<%@ include file="/common/plateform/include/common-base.jsp"%>
	<title>定时任务管理</title>
	<!-- Tell the browser to be responsive to screen width -->
</head>

<!-- Part 一、 以下是body主体内容的模块区域 -->
<body class="hold-transition ${sysColor} sidebar-mini">
<div class="wrapper">

	<!-- top start -->
	<%@include file="/common/plateform/top.jsp" %>
	<!-- top end -->
	<!-- left start -->
	<%@include file="/common/plateform/left-project.jsp" %>
	<!-- left end-->

	<div class="content-wrapper">
		<!-- Main start -->
		<section class="content">
			<div id="div_hidden_content" class="hidden" style="display:none;">
				<div id="hidden_common_final">
					<!-- temp="hidden_common_final" start -->
					<input name="mainObjName" type="hidden" value="uctUser">
					<input name="mainObjPrimaryKey" type="hidden" value="userId">
					<input name="objNameAll" type="hidden" value="uctUser">
					<!-- temp="hidden_common_final" end -->
				</div>
				<!-- temp="delForm_hidden" start -->
				<div id="delForm_hidden">
				</div>
				<!-- temp="delForm_hidden" end -->
			</div>
			<div class="row">
				<div class="col-xs-12">

					<!------- 列表 start -------->
					<div class="box box-success">
						<form id="searchForm" action="javascript:;">
							<div id="searchForm_hidden">
								<input type="hidden" name="sysName" value=""/>
							</div>
						</form>
						<!--列表title  start -->
						<div class="box-header with-border">
							<h3 class="box-title"><i class="fa fa-table"></i> 定时任务列表
								<button  onclick="toAdd();" class="btn btn-primary" type="button"><i class="fa fa-plus-circle"></i> 增加任务 </button>
								<button  onclick="executeTask('','','start');" class="btn btn-success" type="button"><i class="fa fa-play-circle"></i> 启动全部任务 </button>
								<button  onclick="executeTask('','','stop');" class="btn btn-danger" type="button"><i class="fa fa-stop-circle"></i> 停止全部任务 </button>
							</h3>
							<p class="fx8 f12">数据来源：<span id="span_source">file</span></p>
						</div>
						<div class="box-body">
							<table id="dataList" class="table table-bordered table-hover">
								<thead class="bg-success">
								<tr>
									<th>名称/描述</th>
									<th>间隔类型</th>
									<th>启止时点/间隔 时:分:秒 说明</th>
									<th>开启类型</th>
									<th>状态</th>
									<th>操作</th>
								</tr>
								</thead>
								<tbody id="dataList-body">

								</tbody>
							</table>
						</div>

						<div class="box-footer text-center">
							<ul id="dataList-page" class="pagination">
							</ul>
						</div>
					</div>
					<!------- 列表 end -------->
				</div>
			</div>

			<div win-title="添加窗口" class="modal fade" id="my_modal_add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog" style="width:70%;">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
								×
							</button>
							<h4 class="modal-title">
								<font color="red">定时任务添加/修改</font> 
							</h4>
						</div>

						<div class="modal-body">

							<div class="nav-tabs-custom">
								<ul class="nav nav-tabs" id="myTab-add">
								</ul>

								<!-- tab content start -->
								<div class="tab-content">

									<div class="tab-pane active" id="tabAdd_1">
										<form class="form-horizontal addFormBody" role="form" id="addForm1" action="javascript:void(0)">

											<!-- temp="addForm1_hidden" start -->
											<input type="hidden" class="formToken"  name="formToken" />
											<input type="hidden" class="clean" name="taskKey" data-name="task.taskKey"/>
											<input type="hidden" value="" readonly="readonly" name="sysName"/>
											<!-- temp="addForm1_hidden" end -->

											<!-- temp="addForm1_content" start -->
											<div  id="addForm1_content">


												<table class="table table-bordered bordercolor">
													<tbody>
													<tr>
														<td class="active" align="right"><label class="form-control-static">任务名称：</label></td>
														<td colspan="3">
															<div class="form-group">
																	<input type="text"  data-name="task.description" name="description" class="form-control clean" maxlength="100" placeholder="必填项，中文标题说明" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" />
															</div>
														</td>
													</tr>
													<tr>
														<td class="active" align="right"><label class="form-control-static">执行文件：</label></td>
														<td colspan="3">
															<div class="form-group">
																<input type="text" data-name="task.className" name="className" class="form-control clean" maxlength="100" placeholder="必填项，class全地址，如：com.apache.portal.thread.TestSchedulderJob" data-bv-notempty="true" data-bv-notempty-message="此项不能为空"/>
															</div>
														</td>
													</tr>
													<tr>
														<td class="active" align="right"><label class="form-control-static">启用任务IP：</label></td>
														<td>
															<div class="form-group">
																<input type="text"  data-name="task.serverIp" name="serverIp" class="form-control clean" maxlength="20" placeholder="非必填，默认portal服务端IP"/>
															</div>
														</td>
														<td class="active" align="right"><label class="form-control-static">任务类型：</label></td>
														<td>
															<div class="form-group">
																<select name="taskType" id="taskType" data-name="task.taskType" class="form-control">
																	<option value="" selected="selected">自定义类</option>
																	<option value="remote">远程调用</option>
																</select>
															</div>
														</td>
													</tr>
													<tr>
														<td class="active" align="right"><label class="form-control-static">间隔类型：</label></td>
														<td>
															<div class="form-group">
																<select name="intervalType" data-name="task.intervalType"  id="intervalType" class="form-control" data-bv-notempty="true" data-bv-notempty-message="此项不能为空">
																	<option value="0">时间</option>
																	<option value="1" selected="selected">每天</option>
																</select>
															</div>
														</td>
														<td class="active" align="right"><label class="form-control-static">开启类型：</label></td>
														<td>
															<div class="form-group">
																<select name="taskStatus" id="taskStatus" data-name="task.taskStatus" class="form-control" data-bv-notempty="true" data-bv-notempty-message="此项不能为空">
																	<option value="0" selected="selected">手动开启</option>
																	<option value="1">自动开启</option>
																</select>
															</div>
														</td>
													</tr>
													<tr>
														<td class="active" align="right"><label class="form-control-static">间隔时间：</label></td>
														<td colspan="3">
															<div class="form-group">
																<div class="form-group col-sm-3">
																	<input class="form-control clean" title="0~23" data-name="task.hour" name="hour" data-options="required:true,validType:'number'" size="10"  placeholder="如：0~23"  maxlength="2" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" data-bv-regexp="true" data-bv-regexp-regexp="^[0-9]{1,2}$" data-bv-regexp-message="必须是1-2位数字"/>
																</div>
																<span class="col-sm-1 form-control-static" >时</span>

																<div class="form-group col-sm-3">
																	<input class="form-control clean" title="0~59" data-name="task.minute" name="minute" data-options="required:true,validType:'number'" size="10"   placeholder="如：0~59" maxlength="2" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" data-bv-regexp-regexp="^[0-9]{1,2}$" data-bv-regexp-message="必须是1-2位数字"/>
																</div>
																<span class="col-sm-1 form-control-static" >分</span>

																<div class="form-group col-sm-3">
																	<input class="form-control clean" title="0~59" data-name="task.second" name="second" data-options="required:true,validType:'number'" size="10"   placeholder="如：0~59"  maxlength="2" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" data-bv-regexp-regexp="^[0-9]{1,2}$" data-bv-regexp-message="必须是1-2位数字"/>
																</div>
																<span class="col-sm-1 form-control-static" >秒</span>
															</div>
														</td>
													</tr>
													<tr>
														<td class="active" align="right"><label class="form-control-static">启止时点：</label></td>
														<td colspan="3">
															<div class="form-group">
																<div class="form-group col-sm-3">
																	<input class="form-control clean" title="0~23" data-name="task.startTime" name="startTime" data-options="required:true,validType:'number'" size="10"  placeholder="如：0~23" maxlength="2" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" data-bv-regexp-regexp="^[0-9]{1,2}$" data-bv-regexp-message="必须是1-2位数字"/>
																</div>
																<span class="col-sm-1 form-control-static">时</span>
																<label class="col-sm-2 control-label  form-control-static" > 至 </label>
																<div class="form-group col-sm-3">
																	<input class="form-control clean" title="0~23" data-name="task.endTime" name="endTime" data-options="required:true,validType:'number'" size="10"  placeholder="如：0~23" maxlength="2" data-bv-notempty="true" data-bv-notempty-message="此项不能为空" data-bv-regexp-regexp="^[0-9]{1,2}$" data-bv-regexp-message="必须是1-2位数字"/>
																</div>
																<span class="col-sm-1 form-control-static">时</span>
															</div>
														</td>
													</tr>
													</tbody>
												</table>



											</div>
											<!-- temp="addForm1_content" end -->

											<div class="panel-body">
												<div class="col-sm-12">
													<div class="box-footer text-center">

														<button class="btn btn-success pull-left" type="button" onclick="mytools.closeModal('my_modal_add');"> 取消 </button>
														<button class="btn btn-danger pull-right" type="button" onclick="submitForm1('addForm1','');" data-temp-event="addForm1_hidden"> 提 交 </button>
													</div>
												</div>
											</div>


										</form>
									</div>

								</div>
								<!-- tab content e -->
							</div>

						</div>
					</div>
					<!-- /.modal-content -->
				</div>
			</div>



			<!-- Part 二、以下是template模板定义的模块区域 -->
			<script type="text/template" id="dataList-template">
				<? for ( var i = 0; i < rows.length; i++) {?>
				<tr>
					<td>
						<?=strUtil.doNull(rows[i].description,'')?> <?if(!strUtil.isNull(source)){?> [<?=strUtil.doNull(rows[i].sysName,'')?>] <?}?><br/>
						<?=strUtil.doNull(rows[i].className,'')?>
					</td>
					<td><?if(rows[i].intervalType=='0'){?>时间<?}else{?>每天<?}?></td>
					<td>
						<?if(rows[i].intervalType=='0'){?>
							每天<?=rows[i].startTime?>点~<?=rows[i].endTime?>点期间（含）<br/>每间隔[<?=rows[i].hour?>小时<?=rows[i].minute?>分<?=rows[i].second?>秒]执行一次
						<?}else{?>
							每天<?=rows[i].startTime?>点~<?=rows[i].endTime?>点期间（含）<br/>只在[<?=rows[i].hour?>时<?=rows[i].minute?>分<?=rows[i].second?>秒]执行一次
						<?}?>
					</td>
					<td><?if(rows[i].taskStatus=='0'){?>手动开启<?}else{?>自动开启<?}?></td>
					<td><?if(rows[i].openStart==true){?><font color='green'>开启</font><?}else{?><font color='red'>未开启</font><?}?></td>
					<td>
						<?if(rows[i].openStart==true){?>
						<button type="button" class="btn btn-danger btn-xs" onclick="executeTask('<?=rows[i].taskKey?>','<?=rows[i].serverIp?>','stop')">关闭</button>
						<?}else{?>
						<button type="button" class="btn btn-success btn-xs" onclick="executeTask('<?=rows[i].taskKey?>','<?=rows[i].serverIp?>','start');">开启</button>&nbsp;
						<?if(rows[i].openStart==false){?><button type="button" class="btn btn-warning btn-xs" onclick="editInfo('<?=rows[i].taskKey?>','<?=rows[i].openStart?>','<?=rows[i].serverIp?>');">修改</button>&nbsp;
						<button type="button" class="btn btn-danger btn-xs" onclick="delInfo('<?=rows[i].taskKey?>','<?=rows[i].openStart?>','<?=rows[i].serverIp?>');">删除</button><?}?>
						<?}?>
					</td>
				</tr>
				<?}?>
			</script>

			<!-- Part 三、 以下是js模块区域 -->
			<script>
                var clickMenu = "task-list";
                var myPage,dataListId,searchFormId;
                var defSysEname = strUtil.doNull(strUtil.getLocalStorage("sysEname"), "");
                myPage = 10;//定义列表数据
                dataListId = "dataList";//显示列表数据div的id
                searchFormId = "searchForm";//搜索表单Id
                $("#tabAdd_1").find("input[name='sysName']").val(defSysEname);
                $("#"+searchFormId).find("input[name='sysName']").val(defSysEname);

                $(function () {
                    //1、加载分页列表数据
                    // console.log(defSysEname)
                    getTableData();

                    //2、控制是否启用token
                    //setToken();

                });

                $(function () {
                    //设置数据行选中效果
                    $('#'+dataListId+' tbody').on('click','tr', function (e) {
                        if ( $(this).hasClass('selected') ) {
                        }
                        else {
                            $('tr.selected').removeClass('selected');
                            $(this).addClass('selected');
                        }
                        //var id = $('tr.selected th').eq(0).html();
                    } );
                });

                //给模态窗口内form表单内的所有支持必填项的元素注入校验
                $(".modal").on('shown.bs.modal', function () {
                    $(this).find("form").each(function(){
                        var formId = $(this).attr("id");
                        if(!strUtil.isNull(formId)){
                            formId="#"+formId;
                            setValidate(formId);//定义add表单验证属性
                            mytools.cleanValidate(formId);//清空上次校验规则提示
                        }
                    });
                });

                //打开添加modal
                function toAdd(){
                    mytools.cleanData("#addForm1");//清空表单元素上次填写的内容；
                    $(".datepicker").val("");
                    $("#my_modal_add").modal("show");
                }
                //读取（查询、编辑）数据
                function editInfo(id,openStatus,ip){
                    var url = '${ctx}/task/add.action';
                    mytools.cleanData(".addFormBody");//清空表单元素上次填写的内容；
                    $.ajax({
                        type:'get',
                        url:url,
                        data:{"key":id,"sysName":defSysEname,"serverIp":ip},
                        async:false,
                        dataType:"json",
                        success: function(myData){
                            // console.log(myData);
                            //反显加载数据
                            FormUtil.loadView("task", myData);
                            $('#my_modal_add').modal('show');
                        }
                    });
                }
                //逻辑删除
                function delInfo(id,ip){
                    var index_submit = layer.confirm('您确定要删除信息吗？', {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
                        , function(){
                            layer.close(index_submit);
                            $.ajax({
                                type: "post",
                                url: "${ctx}/task/del.action",
                                data:{"key":id,"sysName":defSysEname,"serverIp":ip},
                                dataType: "json",
                                success: function(data){
                                    var result = data;//jQuery.parseJSON(data);
                                    if(result.flag=='T'){
                                        refresh();
                                    }else{
                                        layer.alert("删除失败！");
                                    }
                                }
                            });
                        });
                }

                function executeTask(taskKey,serverIp,type){
                    var url ="${ctx}/task/stop.action";
                    if("start"==type){
                        url ="${ctx}/task/start.action";
                    }
                    var index_submit = layer.confirm("您确定要["+type+"]全部任务吗？", {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
                        , function(){
                            layer.close(index_submit);
                            $.ajax({
                                type: "post",
                                url: url,
                                data:{"key":taskKey,"sysName":defSysEname,"serverIp":serverIp},
                                dataType: "json",
                                success: function(data){
                                    var result = data;//jQuery.parseJSON(data);
                                    if(result.flag=='T'){
                                        layer.alert("操作成功！");
                                        refresh();
                                    } else{
                                        layer.alert("操作失败！");
                                    }
                                }
                            });
                        });
                }
                //加载列表数据
                function getTableData(){
                    $.ajax({
                        type:'get',
                        url:"${ctx}/task/list!data.action",
                        data:$("#"+searchFormId).serialize(),
                        dataType:'json',
                        success: function(myData){
                            console.log(myData,"111111111");
                            var myDataNew = eval(myData);
                            var source = myData.source;
                            if("file"==source){
                                $("#span_source").text("file");
                                myDataNew.source = "";
                            }else{
                                $("#span_source").text("db");
                                myDataNew.source = source;
                            }
                            if(myData.total=="0"){
                                $("#dataList-body").html("");
                            }else{
                                var data = baidu.template(dataListId+"-template",myDataNew);
                                $("#"+dataListId+"-body").html(data);
							}
                        }
                    });
                }


                //提交tab1表单数据
                function submitForm1(formId,tabId){
                    //校验规则-表单提交时触发
                    var validate = $('#'+formId).data('bootstrapValidator').validate();
                    if(!validate.isValid()){ //如果校验不通过就返回
                        return;
                    }
                    var index_submit = layer.confirm('您确定要保存信息吗？', {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
                        , function(){
                            var result = submitForm(formId,tabId);
                            if(result){
                                layer.alert("提交成功！", {closeBtn: 0 });
                                mytools.closeModal("my_modal_add");
                                refresh();
                                setToken();
                                if(!strUtil.isNull(tabId)){
                                    $('.nav-tabs a[href=\"#'+tabId+'\"]').tab('show'); // Select tab by name
                                }
                            }
                        });

                }
                //提交表单数据
                function submitForm(formId,tabId){
                    var result;
                    var index_load = layer.load(1, {shade: false});
                    $.ajax({
                        type:'post',
                        url:'${ctx}/task/save.action',
                        data:$("#"+formId).serialize(),
                        async:false,
                        dataType:'json',
                        success: function(myData){
                            console.log(myData);
                            if(myData.flag=="T"){
                                result = myData;
                            }else{
                                setToken();
                                layer.alert(myData.msg);
                            }
                            layer.close(index_load);
                        },
                        error: function (e) {
                            layer.close(index_load);
                        }
                    });
                    return result;
                }

                //刷新
                function refresh(){
                    getTableData();
                }
                //设置token
                function setToken(){
                    $.ajax({
                        type:'get',
                        url:'${ctx}/sendPage/token?token=true',
                        dataType:'text',
                        success: function(myData){
                            console.log(myData);
                            $('.formToken').val(myData);
                        }
                    });
                }


                /**** Part 四、以下是自定义新增方法  ****/
//1.定义校验规则-定义
                function setValidate(id){
                    $(id).each(function(){
                        $(this).bootstrapValidator({
                            feedbackIcons: {
                                valid: 'glyphicon glyphicon-ok',
                                invalid: 'glyphicon glyphicon-remove',
                                validating: 'glyphicon glyphicon-refresh'
                            },/** 以下需要结合实际业务清空补充个表单元素的验证规则 **/
                            fields:{
                                /** 可自定义新增验证规则
                                 "uctUser.userEname":{
		    		 validators: {
		    			 regexp: {
		    				 regexp: /^[0-9]+$/,
		                      message: '只能是数字'
		                  }
		              }
		    	}
                                 **/
                            }
                        });
                    });
                }


			</script>
		</section>
		<!-- Main end -->
	</div>
</div>
<!-- /.content-wrapper -->
<!-- foot start -->
<%@include file="/common/plateform/foot.jsp" %>
<!-- foot start -->
</body>
</html>


